import 'package:audio_session/audio_session.dart';
import 'package:brage/brage.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/config/device_token_manger.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();

  void addChatListener() {
    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      state.tag,
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          state.player.setAsset('images/music_reveice.mp3');
          final session = await AudioSession.instance;
          session.configure(const AudioSessionConfiguration.music());
          state.player.play();
          EMClient.getInstance.chatManager.getUnreadMessageCount().then((value) {
            Brage().setIOSBrage(brage: value);
            LogUtil.e(tag: 'app启动添加消息监听','触发送角标更新');
            EventBus.instance.commit(eventName:EventKeys.chatUpdateBadge,data: value);
          });
        },
      ),
    );
  }

  // 获取华为token
  getToken() async {
    const channelId = 'com.example.app/get/token'; // 定义与原生端相同的通道名称
    const MethodChannel methodChannel = MethodChannel(channelId);
    // final String token = await methodChannel.invokeMethod('myMethod');
    // if(token.isNotEmpty){
    //   DeviceTokenManger.instance.setHuaWei(token);
    // }
    // EMClient.getInstance.pushManager.updateHMSPushToken(token);
    // LogUtil.e('flutter调用安卓返回token: $token');
    methodChannel.setMethodCallHandler(_handleMethodCall);
  }

  // 处理从原生端发送的令牌数据
  Future<void> _handleMethodCall(MethodCall call) async {
    switch (call.method) {
      case 'onTokenReceived':
        final String token = call.arguments as String;
        if(token.isNotEmpty){
          DeviceTokenManger.instance.setHuaWei(token);
          EMClient.getInstance.pushManager.updateHMSPushToken(token);
        }
        LogUtil.e('安卓获取到token后主调调用flutter: $token');
        return;
      default:
        throw PlatformException(
            code: 'NotImplemented',
            details: "Method '${call.method}' not implemented");
    }
  }
}
